#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>

int i = 0;
int thread_sig = 0;

sem_t sig_1;
sem_t sig_2;
sem_t sig_3;

void *t1(void *arg)
{
    while(1) {
        sem_wait(&sig_1);
        printf("1\n");
        sem_post(&sig_2);
    }

    return NULL;
}

void *t2(void *arg)
{
    while(1){
        sem_wait(&sig_2);
        printf("2\n\n");
        sem_post(&sig_3);
    }

    return NULL;
}

int main(int argc, char *argv[])
{
    
    pthread_t tid1;
    pthread_t tid2;
    int pc_1;
    int pc_2;

    sem_init(&sig_1, 0, 0);
    sem_init(&sig_2, 0, 0);
    sem_init(&sig_3, 0, 1);
    

    pc_1 = pthread_create(&tid1, NULL, t1, NULL);

    if (pc_1 != 0) {
        printf("pc_1: %s\n", strerror(pc_1));
        return -1;
    }

    pc_2 = pthread_create(&tid2, NULL, t2, NULL);

    if (pc_2 != 0) {
        strerror(pc_2);
        return -1;
    }

    while(1) {
        sem_wait(&sig_3);
        printf("3\n");
        sem_post(&sig_1);
        sleep(1);
    }


    sem_destroy(&sig_1);
    sem_destroy(&sig_2);
    sem_destroy(&sig_3);

    return 0;
}
